package cn.wisenergy.pai.monitor.linux.parser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HostSpot implements Serializable{
	
	private static final long serialVersionUID = 7930980083842041686L;
	private static final Logger LOG=LoggerFactory.getLogger(HostSpot.class);
	private String ip;
	private String hostName;
	private static HostSpot host;
	
	public static synchronized HostSpot getCurrentHostSpot(){
		if(host == null ){
			host=new HostSpot();
			InetAddress inet;
			String ip ="UnknownHost";
			String hostName="UnknownHost";
			try {
				inet = InetAddress.getLocalHost();
				ip=inet.toString().substring(inet.toString().indexOf("/")+1);   
			    hostName=inet.toString().substring(0,inet.toString().indexOf("/")); 
			} catch (UnknownHostException e) {
				LOG.warn("can't get hostname and ip");
			}   
	       
	        host.setHostName(hostName);
	        host.setIp(ip);
		}
		return host;
	}
	
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getHostName() {
		return hostName;
	}
	public void setHostName(String hostName) {
		this.hostName = hostName;
	}
	@Override
	public String toString() {
		return "HostSpot [ip=" + ip + ", hostName=" + hostName + "]";
	}
	@Override
	public byte[] toBytes() throws IOException {
		ByteArrayOutputStream bytesOutput=new ByteArrayOutputStream();
		DataOutputStream dataOutput=new DataOutputStream(bytesOutput);
		if(ip != null){
			dataOutput.writeUTF(ip);
		}
		if(hostName != null){
			dataOutput.writeUTF(hostName);
		}
		byte[] result=bytesOutput.toByteArray();
		dataOutput.close();
		bytesOutput.close();
		return result;
	}
	@Override
	public void toObject(byte[] ba) throws IOException {
		ByteArrayInputStream bytesInput=new ByteArrayInputStream(ba);
		DataInputStream dataInput=new DataInputStream(bytesInput);
		if(dataInput.available()>0){
			ip=dataInput.readUTF();
		}
		if(dataInput.available()>0){
			hostName=dataInput.readUTF();
		}
		dataInput.close();
		bytesInput.close();
		
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((ip == null) ? 0 : ip.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		HostSpot other = (HostSpot) obj;
		if (ip == null) {
			if (other.ip != null)
				return false;
		} else if (!ip.equals(other.ip))
			return false;
		return true;
	}

}
